package com.lfy.utils;


import com.lfy.modules.common.custom.BatchDownFIleParams;
import com.lfy.modules.common.custom.FileService;
import com.lfy.modules.common.custom.WebShareDownloadVO;
import com.lfy.modules.common.custom.constants.FileConstant;
import com.lfy.modules.common.custom.constants.FileTypeEnum;
import com.lfy.modules.common.domain.FileUrlVO;
import com.lfy.modules.common.domain.R;
import com.lfy.modules.common.domain.entity.UserEntity;
import com.lfy.modules.common.intercept.AuthHandlerInterceptor;
import com.lfy.modules.common.utils.JsonUtils;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description： minio工具类
 * @version：1.0
 */
@Slf4j
public class MinioUtil implements FileService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Autowired
    private ThreadPoolExecutor mainThreadPool;

    @Resource
    private Environment env;

    @PostConstruct
    public void init() {
        log.info("minio client init success");
        existBucket(bucketName);
    }

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * description: 上传文件
     *
     * @param multipartFile
     * @return: java.lang.String
     */
    public List<String> upload(MultipartFile[] multipartFile) {
        List<String> names = new ArrayList<>(multipartFile.length);
        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String pref = fileName.split("\\.")[0];
            String type = getFileType(fileName);
            fileName = pref + "_" + System.currentTimeMillis() + type;
            InputStream in = null;
            try {
                in = file.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(in, in.available(), -1)
                        .contentType(file.getContentType())
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            names.add(fileName);
        }
        return names;
    }

    /**
     * description: 上传文件
     *
     * @param multipartFile
     * @return: java.lang.String
     */
    @Override
    public List<String> upload(MultipartFile[] multipartFile, String dir) {
        List<String> names = new ArrayList<>(multipartFile.length);
        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();

            assert fileName != null;
            String pref = fileName.split("\\.")[0];
            String type = getFileType(fileName);
            fileName = pref + "_" + System.currentTimeMillis() + type;
            InputStream in = null;
            try {
                in = file.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(dir.concat(fileName))
                        .stream(in, in.available(), -1)
                        .contentType(file.getContentType())
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            names.add(dir.concat(fileName));
        }
        return names;
    }


    private static String getFileType(String fileName) {
        int i = fileName.lastIndexOf(".");
        if (i == -1) {
            throw new IllegalArgumentException("文件名格式不正确");
        }
        return fileName.substring(i);
    }

    /**
     * description: 上传文件
     *
     * @return: java.lang.String
     */
    @Override
    public String uploadSingle(MultipartFile file, String dir) {
        String fileName = file.getOriginalFilename();

        assert fileName != null;
        String pref = fileName.split("\\.")[0];
        String type = getFileType(fileName);
        fileName = pref + "_" + System.currentTimeMillis() + type;
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(dir.concat(fileName))
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return dir.concat(fileName);
    }

    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */

    public ResponseEntity<byte[]> download(String fileName) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Collections.singletonList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    @Override
    public ResponseEntity<byte[]> download(String name, String fileName) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();

            headers.add("Content-Disposition", "attachment;filename=" + name);

            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    @Override
    public void downloadToStream(String name, String path,Integer fileType, HttpServletResponse response) {
        log.info("begin download file，fileName:{}",name);
        try (InputStream originalStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(path)
                .build())){
            ServletOutputStream out = response.getOutputStream();

            byte[] buffer = new byte[1024 * 10];
            int bytesRead;
            //单独处理一下文本
            setContentType(fileType,response);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String encodedFileName = URLEncoder.encode(name,  "UTF-8").replace("+", "%20");

            response.setHeader("Content-Disposition", String.format("attachment; filename*=utf-8''%s", encodedFileName));


            while ((bytesRead = originalStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            log.info("end download success,fileName:{}", name);
        } catch (Exception e) {
            // 处理异常
            log.error("Error occurred while downloading file from Minio", e);

        }

    }
    public void setContentType(Integer fileType,HttpServletResponse response){
        if (FileTypeEnum.DOCUMENT.getCode().equals(fileType)){
            response.setContentType("text/plain;charset=UTF-8");        }
    }






    @Override
    public List<WebShareDownloadVO> batchDownload(List<BatchDownFIleParams> params) {
        if (CollectionUtils.isEmpty(params)){
            return Collections.emptyList();
        }
        List<CompletableFuture<WebShareDownloadVO>> futures = params.stream()
                .map(item -> CompletableFuture.supplyAsync(() ->{
                    WebShareDownloadVO webShareDownloadVO = new WebShareDownloadVO();
                    webShareDownloadVO.setFileName(item.getFileName());
                    ResponseEntity<byte[]> download = download(item.getFileName(), item.getFilePath());
                    webShareDownloadVO.setResponseEntity(download);

                    return webShareDownloadVO;
                } , mainThreadPool)).collect(Collectors.toList());
        CompletableFuture<List<WebShareDownloadVO>> result = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(item -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
        return result.join();
    }


    /**
     * 批量删除文件对象
     *
     * @param bucketName 存储bucket名称
     * @param objects    对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(DeleteObject::new).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        results.forEach(item -> {
            try {
                item.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return results;
    }

    /**
     * 批量删除文件对象
     *
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(DeleteObject::new).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        results.forEach(item -> {
            try {
                item.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return results;
    }

    /**
     * 批量删除文件对象
     *
     * @param objects 对象名称集合
     */
    @Override
    public void removeFileByNames(List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(DeleteObject::new).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        results.forEach(item -> {
            try {
                item.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

    /**
     * 删除目录
     */
    @Override
    public void removeDir(String dir) {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(dir).recursive(true).build());
        List<String> strings = new ArrayList<>();
        for (Result<Item> result : results) {
            try {
                strings.add(result.get().objectName());
            } catch (Exception e) {
                log.error("文件名读取失败，{}", JsonUtils.toStr(result));
            }
        }

        removeObjects(strings);
    }

    /**
     * 拷贝文件
     *
     * @param source 源文件
     * @param target 目标文件
     */
    @Override
    public void copyFile(String source, String target) {
        try {
            minioClient.copyObject(
                    CopyObjectArgs.builder().bucket(bucketName).
                            source(CopySource.builder().bucket(bucketName).object(source).build()).
                            object(target).build()
            );
        } catch (Exception e) {
            log.error("文件拷贝失败,sourceName:{},targetName:{}", source, target);
        }

    }

    @Override
    public boolean checkChunk(String source) {
        GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(bucketName).object(source).build();
        try {
            InputStream response = minioClient.getObject(getObjectArgs);

            return Objects.nonNull(response);
        } catch (Exception e) {

        }
        return false;

    }

    @Override
    public void uploadChunk(MultipartFile file, String sourcce) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(sourcce)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean merge(String dir, String fileName, Integer cutSize, String mergePath) {
        //构建合并文件参数
        List<ComposeSource> composeSourceStream = Stream.iterate(0, i -> ++i).limit(cutSize).map(item -> ComposeSource.builder().bucket(bucketName).object(dir.concat(String.valueOf(item))).build()).collect(Collectors.toList());
        ComposeObjectArgs build = ComposeObjectArgs.builder().bucket(bucketName).object(mergePath).sources(composeSourceStream).build();
        boolean isSuccess = false;
        try {
            minioClient.composeObject(build);
            isSuccess = true;
        } catch (Exception e) {

        }
        return isSuccess;
    }
}


